﻿using Common.Communal;
using ERP.Domain.Processs;
using MediatR;
using Sell.Api.Read.Application.Command.ProcesssCommand;
using Sell.DTO;
using SqlSugar;
using SqlSugar.Extensions;

namespace Sell.Api.Read.Application.CommandHandlers.ProcesssCommandHandlers
{
    public class ProcessflowCommandHandlers : IRequestHandler<ProcessflowCommand, ApiResult<ApiPaging<processflowdto>>>
    {
        public ISqlSugarClient SqlSugar { get; }
        public ProcessflowCommandHandlers(ISqlSugarClient sqlSugar)
        {
            SqlSugar = sqlSugar;
        }
        /// <summary>
        /// 工序流程列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<ApiPaging<processflowdto>>> Handle(ProcessflowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<processflowdto>> res = new ApiResult<ApiPaging<processflowdto>>();
            res.Code = EnumCode.Ok;
            res.Message = " 工序流程列表显示成功";
            /// 初始化查询：关联 Procure表和Contract表
            var query = SqlSugar.Queryable<ProcessFlow>()
                .LeftJoin<PSrocess>((p, s) => p.ProcessId == s.Id)
                .Where(p => p.IsDelete == false).Select(
                (p, s) => new processflowdto
                {
                     ProcessCount = s.ProcessCount,
                      ProcessCode = s.ProcessCode,
                       ProcessName = s.ProcessName,
                        Id=p.Id,
                         Desc=s.Desc,
                          DeptName=s.DeptName,
                           IsDelete=s.IsDelete,
                            ProcessflowCode = p.ProcessflowCode,
                             ProcessflowName = p.ProcessflowName,
                              ProcessId=p.ProcessId,
                               ProcessTypeId=s.ProcessTypeId,
                                State=s.State,
                                 User=s.User,
                });
            //SqlSugar分页查询实现
            ApiPaging<processflowdto> result = new ApiPaging<processflowdto>();
            result.TotalCount = query.Count();//查询总记录数
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.pagesize);//计算总页数
            result.Data = query.Skip((request.pageindex - 1) * request.pagesize)//跳过前面的记录
                .Take(request.pagesize)//取指定页大小的记录
                .ToList();//执行查询并转为List
            res.Success(result, "查询成功");
            return res;
        }
    }
}
